<template>
    <div class="user-container">
        <el-card>
            <div slot="header">
                <el-breadcrumb separator="/">
                    <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
                    <el-breadcrumb-item>个人中心</el-breadcrumb-item>
                </el-breadcrumb>
            </div>
            <div class="main-container">
                <div class="user-form">
                    <el-form ref="userForm" :model="User" label-width="80px">
                        <el-form-item label="用户名">
                            <el-input v-model="User.username" placeholder="用户名"></el-input>
                        </el-form-item>

                        <el-form-item label="密码">
                            <el-input v-model="User.password" placeholder="密码"></el-input>
                        </el-form-item>

                        <el-form-item label="用户权限">
                            <el-input v-model="User.state.name" disabled></el-input>
                        </el-form-item>
                    </el-form>
                </div>

                <div class="user-avatar">
                    <el-image
                        style="width: 100px; height: 100px"
                        :src="User.avatar"
                        fit="cover"></el-image>

                    <el-button type="primary" @click="updateAvatar" size="mini">更改头像</el-button>
                </div>
            </div>

            <el-dialog title="上传头像" :visible.sync="avatarVis">
                <el-upload
                    class="upload-demo"
                    :action="imageUrl"
                    :headers="headers"
                    :on-remove="handleRemove"
                    :on-success="handleUploadSuccess"
                    :on-error="handleUploadError"
                    list-type="picture-card"
                    multiple
                    :limit="1"
                    :on-exceed="handleExceed"
                    :file-list="fileList">
                    <el-button size="small" type="primary">更改头像</el-button>
                </el-upload>

                <div slot="footer" class="dialog-footer">
                    <el-button @click="cancleUpdateAvatar">取消</el-button>
                    <el-button type="primary" @click="handleUpdateAvatar">确定</el-button>
                </div>
            </el-dialog>

            <div class="operatorBtn">
                <el-button type="primary" @click="handleUpdateUser">保存设置</el-button>
            </div>
        </el-card>
    </div>
</template>

<script>
import { getUser,updateUser } from '@/api/user'

import { uploadImg } from '@/api/uploadImage'

export default {
    name: 'User',

    data() {
        return {
            imageUrl:this.baseURL+"/Image/upload",
            headers:{ 
                Authorization:"Bearer "+JSON.parse(window.localStorage.getItem("result")).token
            },
            avatarVis:false,//更改头像的对话框的出现与消失
            fileList:[],
            User:{},
        };
    },

    created(){ 
        this.getUser()
        this.User = {...this.$store.state.User}
        console.log("user user = ",this.$store.state.User)
    },

    methods: {
        /**
         * 获取用户信息
         */
        getUser(){ 
            let params = { 
                uid:JSON.parse(window.localStorage.getItem("result")).user.uid
            }

            // getUser(params).then(res => { 
            //     this.User = res.data
            // })
            this.$store.dispatch('getUser',params)
        },

        /**
         * 打开更新用户头像的对话框
         */
        updateAvatar(){ 
            /**
             * 1.打开用户头像的对话框
             * 2.赋值 fileList
             */
            this.avatarVis = true
            this.fileList.splice(0)
            let file = { 
                name:this.$store.state.User.avatar,
                url:this.$store.state.User.avatar
            }
            this.fileList.push(file)
        },

        /**
         * 文件上传成功
         */
        handleUploadSuccess(response, file, fileList){
            let fileItem = { 
                name:response,
                url:response
            }

            this.fileList.push(fileItem)
            this.fileList = this.fileList.splice(-1)

            this.$message({ 
                type:'success',
                message:'上传成功'
            })

            console.log("上传成功")
            console.log("res = ",response)
            console.log("file = ",file)
            console.log("fileList = ",fileList)
        },

        /**
         * 文件上传失败
         */
        handleUploadError(err, file, fileList){ 
            this.$message({ 
                type:'error',
                message:'上传文件失败'
            })

            console.log("上传失败")
            console.log("error = ",err.statusText)
            console.log("file = ",file)
            console.log("fileList = ",fileList)
        },

        /**
         * 文件移除操作
         */
        handleRemove(file, fileList){ 
            this.fileList.pop()
            this.$message({ 
                type:'success',
                message:'文件移除成功'
            })
            
        },


        /**
         * 文件数量超出限制
         * 让其在更新文件时执行
         */
        handleExceed(files, fileList){
            console.log("超出文件限制")
            console.log("file = ",files)
            console.log("fileList",fileList)

            if(files.length == 1){ 

                let data = new FormData()
                data.append("file",files[0])

                //发送图片上传请求
                uploadImg(data).then(res => { 
                    let fileItem = { 
                        name:res.data,
                        url:res.data
                    }

                    this.fileList.push(fileItem)
                    this.fileList = this.fileList.splice(-1)
                    console.log("超出文件请求上传成功",res)
                }).catch(err => { 
                    console.log("超出文件请求上传失败",err)
                    this.$message({ 
                        type:'error',
                        message:'更新文件失败'
                    })
                })

            } else { 
                this.$message({ 
                    type:'warning',
                    message:'只能选择一张图片'
                })
            }

            
        },

        /**
         * 关闭更新头像对话框
         */
        cancleUpdateAvatar(){ 
            this.avatarVis = false

            this.fileList.splice(0)
        },

        /**
         * 更新头像处理
         */
        handleUpdateAvatar(){ 
            /**
             * 1.将fileList的值赋值给User.avatar
             * 2.关闭对话框
             */
            // this.$store.state.User.avatar = this.fileList[0].name
            this.User.avatar = this.fileList[0].name
            
            this.avatarVis = false

        },

        /**
         * 更新用户---保存设置
         */
        handleUpdateUser(){ 
            let data = this.User

            updateUser(data).then(res => {
                if(res.data == 1){
                    const result = JSON.parse(window.localStorage.getItem("result"))
                    result.user = data
                    window.localStorage.setItem("result",JSON.stringify(result))
                    this.$store.dispatch('updateUser',data) 
                    this.$message({ 
                        type:'success',
                        message:'保存成功'
                    })
                }   
            })
        }
    },
};
</script>

<style scoped>
.user-container
{
    margin: 20px 30px;
    min-width: 1200px;
}

.main-container{
    display: flex;
    flex-direction: row;
}

.user-form{
    margin-right: 200px;
} 

.operatorBtn{ 
    margin-left: 50px;
}
</style>